<template>
  <!-- 违章费用 -->
  <card :showDivider="false" class="mb-4 w-full" toggle bordered :headerStyle="{ background: '#e8f3ff', padding: '10px 20px' }">
    <template #title>
      <div class="order-expense-card__header">
        <span class="header-tit">
          押金扣款抵扣违章金额：<span class="blue">{{ violationAmount }}元</span>
        </span>
        <span class="header-code">押金抵扣类型：<span class="header-value">违章费用</span></span>
      </div>
    </template>
    <table-index :table="table" :selectedKeys="violationSelectKeys" @selection-change="selectChange" :row-class="getRowClassName">
      <template #expand-icon="{ expanded }">
        <icon-plus-circle style="font-size: 20px; color: #0256ff" v-if="!expanded" />
        <icon-minus-circle style="font-size: 20px; color: #0256ff" v-else />
      </template>
      <template #feeNameSort="{ record }">
        {{ record.feeName }}
      </template>
    </table-index>
  </card>
</template>

<script setup>
  import { ref, defineEmits, defineProps, defineExpose, computed } from 'vue'
  import { useTable } from '@/hooks/table'
  import { decimalAddition } from '@/utils/index'
  import { getViolationFeeListByMemberId } from '@/api/order/sOrder'

  const props = defineProps({
    // 选中的费用列表
    violationFeeList: {
      type: Array,
      default: () => [],
    },
    // 押金信息
    depositInfo: {
      type: Object,
      default: () => ({}),
    },
    // 校验函数
    checkIsExceedFn: Function,
  })
  // 选中数据
  const emits = defineEmits(['update:violationFeeList'])
  const violationSelectKeys = ref([])

  const violationAmount = computed(() => {
    let sum = 0
    props.violationFeeList.forEach((fee) => {
      sum = decimalAddition(sum, fee.cutPaymentAmount)
    })
    return sum
  })

  // 违章费用
  const table = useTable({
    rowSelection: {
      type: 'checkbox',
      showCheckedAll: true,
      onlyCurrent: true,
    },
    pagination: false,
    columns: [
      { title: '费用名称', dataIndex: 'feeName', slotName: 'feeNameSort', fixed: 'left' },
      { title: '费用金额', dataIndex: 'totalAmount', unit: '元' },
      {
        title: '待结金额',
        dataIndex: 'outstandingAmount',
        unit: '元',
        headerCellClass: 'tableCommonRed',
        bodyCellClass: 'tableCommonRed',
      },
      { title: '生成时间', dataIndex: 'createTime', width: 170 },
      { title: '费用应结时间', dataIndex: 'dueDate', width: 170 },
      { title: '违章单号', dataIndex: 'businesCode', width: 160 },
      { title: '关联单号', dataIndex: 'orderCode', width: 170 },
      { title: '车牌号', dataIndex: 'carLicenseNo' },
      { title: '违章时间', dataIndex: 'eventTime', width: 170 },
      { title: '费用状态', dataIndex: 'feeStatusName' },
    ],
    operates: false,
  })

  // 加载数据
  const loadData = () => {
    let dataList = table.dataList
    if (dataList && dataList.length > 0) {
      return false
    }
    const queryParam = {
      pageNumber: 1,
      pageSize: 1000,
      depositId: props.depositInfo.id,
    }
    getViolationFeeListByMemberId(queryParam)
      .then((res) => {
        table.tableLoading = false
        // 数据处理
        const list = res.result.data
        list.forEach((el) => {
          el.mtype = 'MENU'
          el.level = 1
          if (el.feeDetailList?.length > 0) {
            el.children = el.feeDetailList
            el.children.forEach((pl) => {
              pl.id = pl.id + 10000 //因折叠根据id问题(父子级id相同)，数据只做展示，故自定义
              pl.mtype = 'TERM1'
              pl.expand = null
              pl.feeName = pl.itemName
              pl.totalAmount = pl.amount
              pl.disabled = true
              pl.isClass = true
            })
          }
        })
        table.dataList = list
      })
      .finally(() => {
        table.tableLoading = false
      })
  }
  // 费用选择事件
  const selectChange = (selectedKeys) => {
    // 校验当前操作是否超出剩余金额
    // 合计金额
    let totalViolationFee = 0
    if (selectedKeys.length > 0) {
      const checkedFees = table.dataList.filter((item) => selectedKeys.includes(item.id))
      if (checkedFees.length > 0) {
        checkedFees.forEach((item) => {
          totalViolationFee = decimalAddition(totalViolationFee, Number(item.outstandingAmount || 0))
        })
      }
      // 校验是否超出
      const isExceed = props.checkIsExceedFn('violation', totalViolationFee)
      // 未超过
      if (!isExceed) {
        violationSelectKeys.value = selectedKeys
        const temp = []
        checkedFees.forEach((fee) => {
          temp.push({
            feeDetailId: fee.id,
            violationCode: fee.businesCode,
            cutPaymentAmount: fee.outstandingAmount,
          })
        })

        emits('update:violationFeeList', temp)
      }
    } else {
      violationSelectKeys.value = []
      emits('update:violationFeeList', [])
    }
  }
  const getRowClassName = (record) => {
    return record.isClass ? 'arco-table-tr-expand' : ''
  }

  // 清空选中数据
  const reset = () => {
    violationSelectKeys.value = []
    table.dataList = []
  }

  defineExpose({
    loadData,
    reset,
  })
</script>

<style lang="less" scoped>
  .blue {
    color: #1890ff;
  }
  .header-tit {
    font-family: PingFang SC, PingFang SC;
    font-weight: 600;
    font-size: 20px;
    color: #1d2129;
    margin-right: 20px;
  }
  .header-code {
    font-family: PingFang SC, PingFang SC;
    font-weight: 400;
    font-size: 14px;
    color: #4e5969;
    margin-right: 20px;
  }
  .header-value {
    color: #1d2129;
  }
  :deep(.arco-table-expand-btn) {
    width: 20px;
    height: 20px;
    background-color: inherit;
  }
  :deep(.arco-table-expand-btn:hover) {
    width: 20px;
    height: 20px;
    background-color: inherit;
  }
  .fee-wrapper {
    max-height: calc(100vh - 150px);
    overflow: auto;
  }
</style>
